package com.ymk.cmd;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.user.UserInfoBO;
import com.ymk.bo.work.*;
import com.ymk.core.code.cmd.UserCmdCode;
import com.ymk.core.code.cmd.WorkEntryCmdCode;
import com.ymk.core.constants.SysConstants;
import com.ymk.core.constants.WxConstants;
import com.ymk.entity.WorkContentEntry;
import com.ymk.service.IWorkContentEntryService;
import com.ymk.service.IWorkContentService;
import com.ymk.service.IWorkEntryService;
import com.ymk.service.IWorkService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Service
public class WorkEntryPostCmd extends ACmd {
    private final static Logger logger = LoggerFactory.getLogger(WorkEntryPostCmd.class);

    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        WorkEntryBO reqData = super.getData(sign, WorkEntryBO.class);
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild();
        //查询岗位信息
      paramsBuilder.clearParam().addParam("id",reqData.getWorkId());
        WorkBO workBO = workService.get(paramsBuilder.build());
        if (Objects.isNull(workBO)){
            throw new MallException( "岗位不存在");
        }

        //查询用户信息
        paramsBuilder.clearParam().addParam("userId",reqData.getUserId());
        CmdSign userCmd = CmdSign.Builder.newBuild(sign)
                .setSource(paramsBuilder.build())
                .setCmdCode(UserCmdCode.USER_GET)
                .setScope(SysConstants.CMD_SERVER_SCOPE)
                .build();
        UserInfoBO userInfoBO = this.scheduler.schedule(request, userCmd, UserInfoBO.class);
        if (Objects.isNull(userInfoBO)){
            throw new MallException( "用户不存在");
        }
        if (StringUtils.isBlank(userInfoBO.getMobile())){
            throw new MallException( "请获取用户手机号");
        }
        if (userInfoBO.getRealState() != 1){
            throw new MallException( "请用户完成实名认证");
        }

        WorkEntryBO workEntry = new WorkEntryBO();
        workEntry.setWorkId(workBO.getId());
        workEntry.setWorkName(workBO.getWorkName());
        workEntry.setSubsidyAmount(workBO.getSubsidyAmount());
        workEntry.setSubsidyCondition(workBO.getSubsidyCondition());
        workEntry.setInterviewAddress(workBO.getInterviewAddress());
        workEntry.setUserId(userInfoBO.getUserId());
        workEntry.setUserName(userInfoBO.getRealName());
        workEntry.setIdCardNo(userInfoBO.getIdCardNo());
        workEntry.setMobile(userInfoBO.getMobile());

        workEntry.setInterviewTime(workBO.getInterviewTime());
        workEntry.setLongitude(workBO.getLongitude());
        workEntry.setLatitude(workBO.getLatitude());
        workEntry.setSex(workBO.getSex());
        workEntry.setAge(workBO.getAge());
        workEntry.setWorkPers(workBO.getWorkPers());
        workEntry.setHeadUrl(workBO.getHeadUrl());
        workEntry.setIncome(workBO.getIncome());
        workEntry.setPolicyDuration(workBO.getPolicyDuration());
        workEntry.setSubsidyDate(workBO.getSubsidyDate());
        workEntry.setWorkCom(workBO.getRemark());
        workEntry.setWorkPay(workBO.getWorkPay());
        workEntry.setState(workBO.getState());
        this.setCreatedData(sign,workEntry);
        this.workEntryService.post(workEntry);

        //保存岗位其他信息
        paramsBuilder.clearParam().addParam("workId",workBO.getId());
        List<WorkContentBO> workContentBOS = this.workContentService.list(paramsBuilder.build());
        workContentBOS.forEach(workContentBO -> {
            WorkContentEntryBO workContentEntry = new WorkContentEntryBO();
            workContentEntry.setEntryId(workEntry.getId());
            workContentEntry.setContent(workContentBO.getContent());
            workContentEntry.setContentInfo(workContentBO.getContentInfo());
            this.setCreatedData(sign,workContentEntry);
            this.workContentEntryService.post(workContentEntry);
        });
        //给管理员发送入职申请提醒
        //this.sendMessage(workEntry,request,sign);
        //发送短信提醒
       // this.sendMessage(workEntry);
        respSign.setSource(super.getSource(workEntry));
        return respSign;
    }

    private void sendMessage( WorkEntryBO workEntry ) throws TencentCloudSDKException {
        SendSmsRequest req = new SendSmsRequest();
        String[] phoneNumberSet1 = {"+8617521272666"};
        req.setPhoneNumberSet(phoneNumberSet1);

        //短信应用id
        req.setSmsSdkAppId(SysConstants.SMS_SDK_APPID);
        //短信签名内容
        req.setSignName(SysConstants.SIGN_NAME);
        //短信模版id
        req.setTemplateId(SysConstants.TEMPLATE_ID);


        //String[] templateParamSet1 = {"上海美团骑手", "韩紫云", "17725545901","130682199803113170","暂无","暂无"};
        String[] templateParamSet1 = new String[2];

        templateParamSet1[0] = workEntry.getUserName();
        templateParamSet1[1] = workEntry.getMobile();

        req.setTemplateParamSet(templateParamSet1);

        // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
        SendSmsResponse resp = smsClient.SendSms(req);
        // 输出json格式的字符串回包
        logger.info("短信发送结果 ==== "+SendSmsResponse.toJsonString(resp));
    }

    private void sendMessage( WorkEntryBO workEntry,HttpServletRequest request, CmdSign sign) throws Exception {
        ParamsBuilder name1 = ParamsBuilder.newBuild()
                .addParam("value", workEntry.getUserName());
        ParamsBuilder thing2 = ParamsBuilder.newBuild()
                .addParam("value", "你有一条新的求职申请，快进入小程序处理吧");

        ParamsBuilder data = ParamsBuilder.newBuild()
                .addParam("name1", name1.build())
                .addParam("thing2", thing2.build());

        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("template_id", WxConstants.WORK_ENTRY_POST)
                .addParam("data", data.build());

        //查询管理员
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("role", 2);
        CmdSign userCmd = CmdSign.Builder.newBuild(sign)
                .setSource(paramsBuilder.build())
                .setCmdCode(UserCmdCode.USER_LIST)
                .setScope(SysConstants.CMD_SERVER_SCOPE)
                .build();
        List<UserInfoBO> userInfoBOS = this.scheduler.schedule(request, userCmd, UserInfoBO.class, true);

        for (UserInfoBO userInfoBO : userInfoBOS) {
            if (!StringUtils.isBlank(userInfoBO.getWxOpenId())) {
                params.addParam("touser", userInfoBO.getWxOpenId());
                String resData = HttpUtil.post(WxConstants.SEND_MESSAGE, JSON.toJSONString(params.build()));
                JSONObject param = JSON.parseObject(resData);
                logger.info("入职微信通知返回消息 ==== "+param.toString());
            }

        }
    }

    @Override
    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {
        WorkEntryBO reqData = super.getData(sign, WorkEntryBO.class);

        if (StringUtils.isBlank(reqData.getUserId())){
            throw new MallException( "用户id不能为空");
        }
        if (Objects.isNull(reqData.getWorkId())){
            throw new MallException( "岗位id不能为空");
        }


        return null;
    }

    @Override
    public String getCmdCode() {
        return WorkEntryCmdCode.WORK_ENTRY_POST;
    }


    @Autowired
    private SmsClient smsClient;
    @Autowired
    private IWorkService workService;
    @Autowired
    private IWorkEntryService workEntryService;
    @Autowired
    private IWorkContentService workContentService;
    @Autowired
    private IWorkContentEntryService workContentEntryService;
}